import JsCookie from "js-cookie";

/**
 * 用户 token 工具类
 * @type {{}}
 */
const TokenUtils = {

    // token key
    tokenKey: "gsToken",
    // 用户id,昵称 key
    userIdAndNicknameKey: "gsUserInfo",
    // 用户页面访问权限
    userPagePermissionCodesKey: "pagePermissionCodes",

    /**
     * 保存用户token
     */
    saveUserToken: (token) => {
        JsCookie.set(TokenUtils.tokenKey, token, {expires: 1});
    },

    /**
     * 保存当前用户id, 昵称信息
     *
     * @param userId 用户id
     * @param nickname 用户昵称
     */
    saveUserIdAndNickname: (userId, nickname) => {
        const userInfo = {
            userId: userId,
            nickname: nickname
        };
        JsCookie.set(TokenUtils.userIdAndNicknameKey, JSON.stringify(userInfo), {expires: 1});
    },

    /**
     * 保存当前用户页面访问权限
     *
     * @param pagePermissionCodes
     */
    saveUserPagePermissionCodes: (pagePermissionCodes) => {
        JsCookie.set(TokenUtils.userPagePermissionCodesKey, JSON.stringify(pagePermissionCodes), {expires: 1});
    },

    /**
     * 删除用户token
     */
    deleteUserToken: () => {
        JsCookie.remove(TokenUtils.tokenKey);
        JsCookie.remove(TokenUtils.userIdAndNicknameKey);
        JsCookie.remove(TokenUtils.userPagePermissionCodesKey);
    },

    /**
     * 获取当前用户的token
     * <p> 若用户未登录, 该方法会返回空值 </p>
     */
    getCurrentUserToken: () => {
        return JsCookie.get(TokenUtils.tokenKey)
    },

    /**
     * 获取当前用户信息
     * <p> userId: 用户id </p>
     * <p> nickname: 用户昵称 </p>
     */
    getCurrentUserInfo: () => {
        let userIdAndNickname = JsCookie.get(TokenUtils.userIdAndNicknameKey);
        if (userIdAndNickname !== null && userIdAndNickname !== '' && userIdAndNickname !== undefined) {
            return JSON.parse(userIdAndNickname);
        }
        return {
            userId: '',
            nickname: ''
        };
    },

    /**
     * 获取当前用户页面访问权限
     */
    getCurrentPagePermissionCodes: () => {
        let pagePermissionCodes = JsCookie.get(TokenUtils.userPagePermissionCodesKey);
        if (pagePermissionCodes !== null && pagePermissionCodes !== '' && pagePermissionCodes !== undefined) {
            return JSON.parse(pagePermissionCodes);
        }
        return [];
    },

}

export default TokenUtils;
